<template>
  <div class="history-container">
    <h1>历史截图记录</h1>
    <table class="history-table">
      <thead>
      <tr>
        <th>序号</th>
        <th>大棚编号</th>
        <th>时间</th>
        <th>截图</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, index) in cameraData" :key="item.id" @click="selectImage(item)">
        <td>{{ index + 1 }}</td>
        <td>{{ item.device.serialNumber }}</td>
        <td>{{ formatDate(item.createdAt) }}</td>
        <td>
          <img
              v-if="item.localImagePath"
              :src="imageUrls[item.id]"
              alt="Camera Screenshot"
              class="image-preview"
          />
          <span v-else>无截图</span>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useStore } from '@/store/index.js';

const emit = defineEmits(['select-image']); // 定义事件

const cameraData = ref([]);
const imageUrls = ref({});

const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const fetchImageUrl = async (id, localImagePath) => {
  const url = await getImageUrl(localImagePath);
  imageUrls.value[id] = url;
};

const getImageUrl = async (localImagePath) => {
  const userStore = useStore();
  const token = userStore.token;
  const relativePath = convertToRelativePath(localImagePath);
  const filename = relativePath.split('/').pop();

  try {
    const response = await axios.get(`/api/camera_data/image/${filename}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      responseType: 'arraybuffer',
    });

    const binaryString = Array.from(new Uint8Array(response.data))
        .map((byte) => String.fromCharCode(byte))
        .join('');
    const base64 = btoa(binaryString);
    return `data:image/jpeg;base64,${base64}`;
  } catch (error) {
    console.error('获取图片失败:', error);
    return '';
  }
};

const convertToRelativePath = (absolutePath) => {
  const projectRoot = "C:\\Users\\user\\Desktop\\ShiXun\\TiXiJieGou\\achitecture\\src\\main\\resources\\image\\";
  if (absolutePath.startsWith(projectRoot)) {
    return absolutePath.substring(projectRoot.length);
  }
  return absolutePath;
};

const fetchCameraData = async () => {
  try {
    const userStore = useStore();
    const token = userStore.token;
    const response = await axios.get('/api/camera_data/history', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    cameraData.value = response.data;

    cameraData.value.forEach((item) => {
      if (item.localImagePath) {
        fetchImageUrl(item.id, item.localImagePath);
      }
    });

    // 默认选中最后一条数据
    if (cameraData.value.length > 0) {
      const lastItem = cameraData.value[cameraData.value.length - 1];
      selectImage(lastItem);
    }
  } catch (error) {
    console.error('获取摄像头数据失败:', error);
  }
};

const selectImage = (item) => {
  const imageInfo = {
    url: imageUrls.value[item.id],
    serialNumber: item.device.serialNumber,
    time: formatDate(item.createdAt),
  };
  emit('select-image', imageInfo); // 触发事件
};

onMounted(() => {
  fetchCameraData();
});
</script>


<style scoped>
.history-container {
  width: 90%; /* 宽度与表格一致 */
  height: 670px;
  padding: 20px; /* 调整内边距 */
  font-family: 'Roboto', sans-serif;
  background-color: #1e2a38;
  color: #f1f1f1;
  border-radius: 12px;
  margin: 0 auto; /* 居中显示 */
  box-shadow: 0 0 20px 5px rgb(22, 92, 194); /* 深蓝色发光效果 */
  overflow: auto; /* 隐藏溢出内容 */
}

/* 隐藏滚动条 */
.history-container::-webkit-scrollbar {
  width: 0; /* 隐藏垂直滚动条 */
  height: 0; /* 隐藏水平滚动条 */
}

.history-container {
  scrollbar-width: none; /* Firefox 隐藏滚动条 */
}

h1 {
  text-align: center;
  margin-bottom: 40px;
  font-size: 22px;
  color: #417fd9;
  font-weight: bold;
  text-transform: uppercase;
}

.history-table {
  width: 100%; /* 宽度与容器一致 */
  border-collapse: collapse;
  margin-top: 20px;
  font-size: 16px;
}

.history-table th, .history-table td {
  padding: 15px 20px;
  border: 1px solid #333;
  text-align: center;
  font-weight: 500;
}

.history-table th {
  background-color: #0f1b2b;
  color: #7aa3e0;
  border-bottom: 2px solid #3480ee;
}

.history-table td {
  background-color: #263344;
  color: #f1f1f1;
  border-top: 1px solid #333;
}

.history-table tr:nth-child(even) td {
  background-color: #1f2b3d;
}

.history-table tr:hover td {
  background-color: #4b8ff3;
  color: #fff;
}

.image-preview {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-preview:hover {
  transform: scale(1.1);
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8); /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* 确保模态框在最上层 */
}

.modal-content {
  background-color: #1e2a38;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
  max-width: 90%;
  max-height: 90%;
  overflow: auto;
}

.enlarged-image {
  max-width: 100%;
  max-height: 80vh; /* 限制图片最大高度 */
  border-radius: 10px;
}
</style>